package com.milo.concurrent;

import org.junit.Test;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 学习CopyOnWriteArrayList用法
 * @author Milo Lee
 * @date 2022-04-13 11:25
 */
public class CopyOnWriteArrayListTest {

    //并发操作的执行目标
    public static class ConcurrentTarget implements Runnable {
        //并发操作的目标队列
        List<String> targetList = null;
        public ConcurrentTarget(List<String> targetList){
            this.targetList = targetList;
        }

        @Override
        public void run() {
            Iterator<String> stringIterator = targetList.iterator();
            //迭代操作
            while (stringIterator.hasNext()) {
                //迭代操作时,进行列表修改
                String threadName    = Thread.currentThread().getName();
                System.out.println("threadName===="+threadName);
                //修改集合
                targetList.add(threadName);
            }
        }
    }

    /**
     * 测试会报错
     * 测试同步队列:迭代操作时候,更新列表
     */
    @Test
    public void testSynchronizedList(){
        List<String> noSafeList = Arrays.asList("a", "b", "c");
        List<String> synList = Collections.synchronizedList(noSafeList);
        //创建一个执行目标
        ConcurrentTarget target = new ConcurrentTarget(synList);
        for (int i = 0; i < 10; i++) {
            new Thread(target,"线程=="+i).start();
        }
    }

    /**
     * 测试发现不会报错,可以使用CopyOnWriteArrayList容器可以在进行元素迭代的同时进行元素添加操作
     */
    @Test
    public void testCopyOnWriteArrayList(){
        List<String> noSafeList = Arrays.asList("a", "b", "c");
        //创建CopyOnWriteArrayList
        CopyOnWriteArrayList<String> writeArrayList = new CopyOnWriteArrayList<String>(noSafeList);
        //创建一个执行目标
        ConcurrentTarget target = new ConcurrentTarget(writeArrayList);
        for (int i = 0; i < 10; i++) {
            new Thread(target,"线程=="+i).start();
        }
    }

}
